SYSTEMD_SERVICE_NAME=@SYSTEMD_SERVICE_NAME@
SYSTEMD_UNIT_FILE_NAME=@SYSTEMD_UNIT_FILE_NAME@

# if not 0 (uninstall) then 1 or 2 (initial or upgrade)
if [ $1 -ne 0 ]; then
    [ -d @CPACK_ETC_DIR@ ] || %{__mkdir} @CPACK_ETC_DIR@
    
    # place a symlink in /usr/bin targeting the installed binary
    ln -sfn @CPACK_BIN_DIR@/@CPACK_PACKAGE_NAME@ /usr/bin/@CPACK_PACKAGE_NAME@

    # copy the unit file to the systemd unit directory as a regular file
    %{__install} -m 644 @CPACK_SHARE_DIR@/$SYSTEMD_UNIT_FILE_NAME %{_unitdir}/$SYSTEMD_UNIT_FILE_NAME 2>&1

    # delete the old copy of the unit file to reduce confusion; modifying the file with an explanation or warning or
    # link is an alternative to removing it, but that causes unwanted *.rpmsave backups since it is then presumed to be
    # a user modification
    if [ -e @CPACK_SHARE_DIR@/$SYSTEMD_UNIT_FILE_NAME ]; then
        unlink @CPACK_SHARE_DIR@/$SYSTEMD_UNIT_FILE_NAME
    fi
fi

%systemd_post $SYSTEMD_SERVICE_NAME

# update permissions in /var/lib/ziti, /opt/openziti/etc/identities
chown ziti:ziti "@ZITI_STATE_DIR@" || :
chmod -R u=rwX,g=rwX,o= "@ZITI_STATE_DIR@" || :

chown root:ziti "@ZITI_IDENTITY_DIR@" || :
chmod 0770 "@ZITI_IDENTITY_DIR@" || :
find "@ZITI_IDENTITY_DIR@" -maxdepth 1 -name "*.json" -type f -exec chown ziti:ziti "{}" + -exec chmod 0440 "{}" + || :

# remove socket files that were created by older ziti-edge-tunnel versions
rm -f /tmp/ziti-edge-tunnel.sock /tmp/ziti-edge-tunnel-event.sock

# if not 0 (uninstall) then 1 or 2 (initial or upgrade)
if [ $1 -ne 0 ]; then
    # if stdin is a tty
    if [ -t 0 ]; then
        ssize=$(tput cols)
    else
        ssize=80
    fi
    printf '\n'
    printf %"$ssize"s | tr " " "-"
    printf '\n'
    if [ $1 -eq 2 ]; then
        echo "Completed configuration of $SYSTEMD_SERVICE_NAME"
    elif [ $1 -eq 1 ]; then
        echo  "Completed clean install of $SYSTEMD_SERVICE_NAME"\
              "Get started by adding an identity: Start $SYSTEMD_UNIT_FILE_NAME and run:" \
        | fold -w $ssize
        echo '  ziti-edge-tunnel add --jwt "$(< ziti_id.jwt)" --identity "ziti_id"'
    fi
    printf %"$ssize"s | tr " " "-"
    printf '\n\n'
fi
